package com.zheng.coderepo.algorithm;

import org.junit.Assert;
import org.junit.Test;

/**
 * Created by zcz on 2018/5/22.
 */
public class WordReverse {

    public String reverse01(String str) {
        if (str == null || str.length() == 0) {
            return str;
        }
        char[] chars = str.toCharArray();
        reverse(chars, 0, chars.length -1);
        int j = 0;
        for (int i = 0; i <= str.length(); i++) {
            if (i == str.length() || chars[i] == ' ' ) {
                reverse(chars, j, i-1);
                j = i+1;
            }
        }
        return new String(chars);
    }

    private void reverse(char[] chars, int start, int end) {
        while (start < end) {
            char temp = chars[start];
            chars[start] = chars[end];
            chars[end] = temp;
            start++;
            end--;
        }
    }

    @Test
    public void testReverse() {
        Assert.assertEquals("II String a in Words Reverse", reverse01("Reverse Words in a String II"));
        Assert.assertEquals(" II    String a   in Words Reverse  ", reverse01("  Reverse Words in   a String    II "));

    }
}
